import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bmflocation/flutter_bmflocation.dart';
import 'package:flutter_module/data/data_manager.dart';
import 'package:flutter_module/data/ni_data_controller.dart';
import 'package:flutter_module/system/constant_config.dart';
import 'package:flutter_module/system/log_util.dart';
import 'package:flutter_module/system/library_map.dart';
import 'package:flutter_module/viewModels/drawer_manager_viewmodel.dart';
import 'package:flutter_module/viewModels/map_control_viewmodel.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/src/provider.dart';
import 'models/ni_location_model.dart';
import 'ni_map_controller.dart';

// /// 地图创建回调
// typedef NIMapCreatedCallback = void Function(
//     NIMapController mapController, NIDataController dataController);

/// 地图Widget
class NIMapViewWidget extends StatefulWidget {
  /// NIMapWidget构造方法
  const NIMapViewWidget({
    Key? key,
    // required this.onNIMapCreated,
    this.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
    this.layoutDirection,
    this.mapOptions,
  }) : super(key: key);

  // /// 创建mapView回调
  // final NIMapCreatedCallback onNIMapCreated;

  /// 渗透点击事件，接收范围 opaque > translucent > transparent；
  final PlatformViewHitTestBehavior hitTestBehavior;

  /// 嵌入视图文本方向
  final TextDirection? layoutDirection;

  /// map属性配置
  final NIMapOptions? mapOptions;

  @override
  _NIMapWidgetState createState() => _NIMapWidgetState();
}

class _NIMapWidgetState extends State<NIMapViewWidget> {
  ///百度定位
  final LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();
  BaiduLocationAndroidOption option = BaiduLocationAndroidOption(
      // 定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
      locationMode: BMFLocationMode.hightAccuracy,
// 是否需要返回地址信息
      isNeedAddress: false,
// 是否需要返回海拔高度信息
      isNeedAltitude: true,
// 是否需要返回周边poi信息
      isNeedLocationPoiList: false,
// 是否需要返回新版本rgc信息
      isNeedNewVersionRgc: true,
// 是否需要返回位置描述信息
      isNeedLocationDescribe: true,
// 是否使用gps
      openGps: true,
// 可选，设置场景定位参数，包括签到场景、运动场景、出行场景
      locationPurpose: BMFLocationPurpose.sport,
// 坐标系
      coordType: BMFLocationCoordType.gcj02,
// 设置发起定位请求的间隔，int类型，单位ms
// 如果设置为0，则代表单次定位，即仅定位一次，默认为0
      scanspan: 1000);

  late final DrawerManagerViewModel _providerDrawerRead;
  late final MapControlViewModel _providerMapControlRead;
  final _gestureRecognizers = <Factory<OneSequenceGestureRecognizer>>{
    Factory<OneSequenceGestureRecognizer>(() => EagerGestureRecognizer()),
  };

  @override
  void initState() {
    LogUtil.instance.printf("初始化地图");

    /// 动态申请定位权限
    requestPermission();

    super.initState();
  }

  ///初始化时，在initState()之后立刻调用
  @override
  void didChangeDependencies() {
    MediaQueryData mediaQueryData = MediaQuery.of(context);
    ConstantConfig.screenSize = mediaQueryData.size;
    ConstantConfig.devicePixelRatio = mediaQueryData.devicePixelRatio;
    ConstantConfig.screenOrientation =
        mediaQueryData.size.height > mediaQueryData.size.width;
    _providerDrawerRead = context.read<DrawerManagerViewModel>();
    _providerMapControlRead = context.read<MapControlViewModel>();
    ConstantConfig.numSize = ConstantConfig.screenOrientation==true?2:4;
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    LogUtil.instance.printf("创建地图", tag: "build");

    if (defaultTargetPlatform == TargetPlatform.iOS) {
      // iOS
      return UiKitView(
        viewType: NINativeViewType.sMapView,
        // 原生交互时唯一标识符
        onPlatformViewCreated: _onPlatformViewCreated,
        // 创建视图后的回调
        gestureRecognizers: _gestureRecognizers,
        // 透传手势
        hitTestBehavior: widget.hitTestBehavior,
        // 渗透点击事件
        layoutDirection: widget.layoutDirection,
        // 嵌入视图文本方向
        creationParams: widget.mapOptions == null
            ? NIMapOptions().toJson()
            : widget.mapOptions!.toJson(),
        // 向视图传递参数
        creationParamsCodec: const StandardMessageCodec(), // 编解码器类型
      );
    } else if (defaultTargetPlatform == TargetPlatform.android) {
      return AndroidView(
        viewType: NINativeViewType.sMapView,
        onPlatformViewCreated: _onPlatformViewCreated,
        hitTestBehavior: widget.hitTestBehavior,
        // 渗透点击事件
        layoutDirection: widget.layoutDirection,
        // 底图初始化参数
        creationParams: widget.mapOptions == null
            ? NIMapOptions().toJson()
            : widget.mapOptions!.toJson(),
        // 向视图传递参数
        creationParamsCodec: const StandardMessageCodec(), // 编解码器类型
      );
    } else {
      return Text('flutter_mapapi_map插件尚不支持$defaultTargetPlatform');
    }
  }

  @override
  void dispose() {
    LogUtil.instance.printf("销毁地图widage");
    _locationPlugin.stopLocation();
    super.dispose();
  }

  @override
  void didUpdateWidget(NIMapViewWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  void reassemble() {
    super.reassemble();
  }

  // 动态申请定位权限
  void requestPermission() async {
    // 申请权限
    bool hasLocationPermission = await requestLocationPermission();
    if (hasLocationPermission) {
      // 权限申请通过
    } else {}
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  void _onPlatformViewCreated(int id) {
    LogUtil.instance.printf("地图初始化返回的Id $id");

    ///初始化地图控制器
    MapManager.instance.setNIMapController(NIMapController.withId(id));

    ///初始化数据控制器
    DataManager.instance.setNIDataController(NIDataController.withId(id));

    _providerMapControlRead.initMapEventCallback();

    /// 设置ios端ak
    // LocationFlutterPlugin.authAK("百度地图ak");
    //接受定位回调
    _locationPlugin.setAgreePrivacy(true);
    _locationPlugin.seriesLocationCallback(callback: (BaiduLocation result) {
      LogUtil.instance.printf(
          "定位结果 ： ${result.getMap()}  ${_providerMapControlRead.tracking}");
      MapManager.instance.mapController.updateLocationData(
          NILocation(
              latitude: result.latitude,
              longitude: result.longitude,
              altitude: result.altitude,
              direction: result.course,
              radius: result.radius),
          tracking: _providerMapControlRead.tracking);
      _providerMapControlRead.setLocation(result);
    });
    _providerDrawerRead.initMapOnClickCallback();
    Future.delayed(const Duration(seconds: 1), () {
      _locationPlugin.startLocation();
    });
  }
}
